package com.ice.work.moment.ticket.service.impl;

import com.google.common.collect.Lists;
import com.honeybee.cloud.framework.base.exception.business.BaseBizException;
import com.honeybee.cloud.framework.common.constant.CommonSystemConstant;
import com.honeybee.cloud.framework.common.enums.DataStatusEnum;
import com.honeybee.cloud.framework.common.http.HttpClient;
import com.honeybee.cloud.framework.common.idwork.IdWorker;
import com.ice.work.moment.facade.ticket.constant.TicketUrl;
import com.ice.work.moment.facade.ticket.dto.StationDTO;
import com.ice.work.moment.facade.ticket.mapper.StationConvertMapper;
import com.ice.work.moment.facade.ticket.model.Station;
import com.ice.work.moment.ticket.dao.station.StationRepository;
import com.ice.work.moment.ticket.service.IStationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import static com.ice.work.moment.facade.ticket.enums.TicketBizExceptionEnum.REQUEST_EXP;

/**
 * @Description station
 * @Author DELL
 * @Create 2019-05-24
 * @Since 1.0.0
 */
@Service
@Slf4j
public class StationServiceImpl implements IStationService {

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private HttpClient httpClient;

    @Autowired
    private IdWorker idWorker;

    @Override
    public StationDTO findByCode(String code) throws BaseBizException {
        Assert.notNull(code, "code not null");
        Station station = stationRepository.findByCodeAndDataStatus(code, DataStatusEnum.VALID.key);
        return StationConvertMapper.INSTANCE.toDTO(station);
    }

    @Override
    public Boolean crawlingStation() throws BaseBizException {
        try {
            String result = httpClient.sendGet(TicketUrl.STATION_URL);
            result = result.substring(result.indexOf("@") + 1, result.lastIndexOf("'"));
            log.info("全部车站信息：{}", result);
            String[] stations = result.split("@");
            List<Station> stationList = Lists.newArrayList();
            for (String str : stations) {
                if (StringUtils.isEmpty(str)) {
                    continue;
                }
                log.info("车站信息:{}", str);
                String[] stationStr = str.split("\\|");
                int length = stationStr.length;
                if (length == 0) {
                    continue;
                }
                Station station = new Station();
                if (length > 0) {
                    station.setAbbreviation(stationStr[0]);
                }
                if (length > 1) {
                    station.setChineseName(stationStr[1]);
                }
                if (length > 2) {
                    station.setEnglishName(stationStr[2]);
                }
                if (length > 3) {
                    station.setFullSpelling(stationStr[3]);
                }
                if (length > 4) {
                    station.setStationKey(stationStr[4]);
                }
                if (length > 5) {
                    station.setStationCode(stationStr[5]);
                }
                Station exists = stationRepository.findByCodeAndDataStatus(station.getStationCode(), DataStatusEnum.VALID.key);
                if (Objects.nonNull(exists)) {
                    station.setId(exists.getId());
                } else {
                    station.setDataStatus(DataStatusEnum.VALID.key);
                    station.setCreateAt(new Date());
                    station.setId(idWorker.nextId());
                }
                stationList.add(station);
            }
            return stationRepository.saveOrUpdateBatch(stationList, CommonSystemConstant.BATCH_SIZE);
        } catch (Exception e) {
            log.error("爬取全部车站信息异常", e);
            throw new BaseBizException(REQUEST_EXP.getParentCode(), REQUEST_EXP.getSubCode(), REQUEST_EXP.getMessage());
        }
    }

    @Override
    public List<StationDTO> getStations() throws BaseBizException {
        List<Station> stationList=stationRepository.list();
        return StationConvertMapper.INSTANCE.toDTO(stationList);
    }
}
